package org.epam.szhuk.greenway.adapter;

import java.util.List;

import org.epam.szhuk.greenway.R;
import org.epam.szhuk.greenway.model.LocationFileSelection;

import android.app.Activity;
import android.database.Cursor;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.CompoundButton;
import android.widget.TextView;

public class SelectSpeedFileAdapter extends ArrayAdapter<LocationFileSelection> {

	private final List<LocationFileSelection> list;
	private final Activity context;

	public SelectSpeedFileAdapter(Activity context,
			List<LocationFileSelection> list) {
		super(context, R.layout.speedfile_row, list);
		this.context = context;
		this.list = list;
	}

	static class ViewHolder {
		protected CheckedTextView tt;// = (CheckedTextView) view.findViewById(R.id.checkedTextView1);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = null;
		if (convertView == null) {
			LayoutInflater inflator = context.getLayoutInflater();
			view = inflator.inflate(R.layout.speedfile_row, null);
			final ViewHolder viewHolder = new ViewHolder();
			viewHolder.tt=(CheckedTextView) view.findViewById(R.id.checkedTextView1);
			viewHolder.tt.setOnClickListener(new View.OnClickListener() {		        
				@Override
				public void onClick(View v){
					changeCheckTextState(v);
		        }
			});
			viewHolder.tt.setOnLongClickListener(new View.OnLongClickListener() {
				@Override
				public boolean onLongClick(View v) {
					((Activity)context).openContextMenu(v);
					return true;
				}		        
				
			});
			
			view.setTag(viewHolder);
			viewHolder.tt.setTag(list.get(position));
			
		} else {
			view = convertView;
			((ViewHolder) view.getTag()).tt.setTag(list.get(position));
		}
		ViewHolder holder = (ViewHolder) view.getTag();
		
		holder.tt.setText(list.get(position).getShownName());
		//holder.checkbox.setChecked(list.get(position).isSelected());
		
		holder.tt.setChecked(list.get(position).isSelected());//sets actual selected item
		 
		return view;
	}
	
	public void changeCheckTextState(View v){
		((CheckedTextView) v).toggle();
		if(v.getTag()!=null){
			LocationFileSelection element = (LocationFileSelection) v.getTag();
			//LocationFileSelection element = (LocationFileSelection) holder.tt.getTag();
			element.setSelected(((CheckedTextView) v).isChecked());
		}
	}
}